package com.zhangjingcheng.yunyixia.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zhangjingcheng.yunyixia.pojo.entity.User;
import com.zhangjingcheng.yunyixia.properties.JwtProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT工具类
 * 用于生成和解析JWT Token
 */
@Component
public class JwtUtil {

	@Autowired
	private JwtProperties jwtProperties;
	
	/**
	 * 生成JWT Token
	 * @param user 业务数据，将被包含在token中
	 * @return 生成的JWT Token字符串
	 */
    public String genToken(User user) {
		Map<String, Object> claims = new HashMap<>();
		claims.put("id", user.getId());
		claims.put("nickName", user.getNickName());
		claims.put("password", user.getPassword());
        return JWT.create()
                .withClaim("claims", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpire()))
                .sign(Algorithm.HMAC256(jwtProperties.getKey()));
    }

	/**
	 * 解析JWT Token
	 * @param token 待解析的JWT Token字符串
	 * @return token中包含的业务数据
	 */
    public Map<String, Object> parseToken(String token) {
        return JWT.require(Algorithm.HMAC256(jwtProperties.getKey()))
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();
    }

}
